package com.ikingtech.platform.business.component.picker;

import com.ikingtech.framework.sdk.component.api.CompDepartmentApi;
import com.ikingtech.framework.sdk.component.api.CompPostApi;
import com.ikingtech.framework.sdk.component.api.CompRoleApi;
import com.ikingtech.framework.sdk.component.api.CompUserApi;
import com.ikingtech.framework.sdk.component.model.*;
import com.ikingtech.framework.sdk.context.security.Me;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import com.ikingtech.framework.sdk.web.annotation.PostRequest;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
@ApiController(value = "/component/pick", name = "业务组件-选择组件", description = "业务组件-选择组件")
public class PickerHandler {

    private final CompUserApi compUserApi;

    private final CompDepartmentApi compDepartmentApi;

    private final CompRoleApi compRoleApi;

    private final CompPostApi compPostApi;

    /**
     * 部门选择
     *
     * @param queryParam 查询条件
     * @return 部门选择结果
     */
    @PostRequest(order = 1, value = "/department", summary = "部门选择", description = "部门选择")
    public R<PickResultDTO> departmentPick(@Parameter(name = "queryParam", description = "查询条件")
                                           @RequestBody PickerElementQueryParamDTO queryParam) {
        return R.ok(this.pickDepartment(queryParam.getName(), queryParam.getParentDepartmentId(), queryParam.getRootDepartmentOnly(), queryParam.getDataScopeOnly()));
    }

    /**
     * 角色选择
     *
     * @param queryParam 查询条件
     * @return 选择结果
     */
    @PostRequest(order = 2, value = "/role", summary = "角色选择", description = "角色选择")
    public R<PickResultDTO> rolePick(@Parameter(name = "queryParam", description = "查询条件")
                                     @RequestBody PickerElementQueryParamDTO queryParam) {
        PickResultDTO result = new PickResultDTO();
        result.setRoles(this.pickRole(queryParam.getName()));
        return R.ok(result);
    }

    /**
     * 岗位选择
     *
     * @param queryParam 查询条件
     * @return 选择结果
     */
    @PostRequest(order = 3, value = "/post", summary = "岗位选择", description = "岗位选择")
    public R<PickResultDTO> postPick(@Parameter(name = "queryParam", description = "查询条件")
                                     @RequestBody PickerElementQueryParamDTO queryParam) {
        PickResultDTO result = new PickResultDTO();
        result.setPosts(this.pickPost(queryParam.getName()));
        return R.ok(result);
    }

    /**
     * 指定用户选择
     *
     * @param queryParam 查询条件
     * @return 选择结果
     */
    @PostRequest(order = 4, value = "/specified-user", summary = "指定用户选择", description = "指定用户选择")
    public R<PickResultDTO> specifiedUserPick(@Parameter(name = "queryParam", description = "查询条件")
                                              @RequestBody PickerElementQueryParamDTO queryParam) {
        PickResultDTO result = new PickResultDTO();
        ComponentDepartment rootDept = this.compDepartmentApi.getRootDepartment();
        result.setUsers(this.pickUser(queryParam.getUserIds(),
                queryParam.getName(),
                Tools.Str.isBlank(queryParam.getParentDepartmentId()) ? rootDept.getElementId() : queryParam.getParentDepartmentId(),
                queryParam.getDataScopeOnly()));
        return R.ok(result);
    }

    /**
     * 混合选择
     *
     * @param queryParam 查询条件
     * @return 混合选择结果
     */
    @PostRequest(order = 5, value = "/mix", summary = "混合选择", description = "混合选择")
    public R<PickResultDTO> mixPick(@Parameter(name = "queryParam", description = "查询条件")
                                    @RequestBody PickerElementQueryParamDTO queryParam) {
        ComponentDepartment rootDept = this.compDepartmentApi.getRootDepartment();
        if (Boolean.TRUE.equals(queryParam.getRootDepartmentOnly())) {
            PickResultDTO result = new PickResultDTO();
            result.setRootDepartment(rootDept);
            return R.ok(result);
        }
        // 创建混合选择结果对象
        PickResultDTO result = this.pickDepartment(queryParam.getName(), queryParam.getParentDepartmentId(), queryParam.getRootDepartmentOnly(), queryParam.getDataScopeOnly());
        // 设置用户
        result.setUsers(this.pickUser(queryParam.getUserIds(), queryParam.getName(), result.getRootDepartment().getElementId(), queryParam.getDataScopeOnly()));
        // 设置角色
        result.setRoles(this.pickRole(queryParam.getName()));
        // 设置职位
        result.setPosts(this.pickPost(queryParam.getName()));
        // 返回混合选择结果
        return R.ok(result);
    }

    private PickResultDTO pickDepartment(String deptName, String parentId, Boolean rootDepartmentOnly, Boolean dataScopeOnly) {
        PickResultDTO result = new PickResultDTO();
        ComponentDepartment rootDept = Tools.Str.isBlank(parentId) ? this.compDepartmentApi.getRootDepartment() : this.compDepartmentApi.load(parentId);
        result.setRootDepartment(rootDept);
        List<ComponentDepartment> departments = new ArrayList<>();
        if (!Boolean.TRUE.equals(rootDepartmentOnly)) {
            if (Tools.Str.isNotBlank(deptName)) {
                // 如果查询参数的名称不为空，则根据名称查询部门列表
                departments = this.compDepartmentApi.listByName(deptName);
            } else {
                // 如果查询参数的名称为空，则根据父部门ID查询部门列表
                departments = this.compDepartmentApi.listByParentId(rootDept.getElementId());
            }
        }
        result.setDepartments(Tools.Coll.traverse(departments, compDepartment -> !Boolean.TRUE.equals(dataScopeOnly) || !Me.invalidDataScope(compDepartment.getElementId()), compDepartment -> {
            if (Boolean.TRUE.equals(dataScopeOnly)) {
                compDepartment.setAvailable(Me.exist(compDepartment.getElementId()));
            }
            return compDepartment;
        }));
        return result;
    }

    private List<ComponentRole> pickRole(String roleName) {
        return this.compRoleApi.listByName(roleName);
    }

    private List<ComponentPost> pickPost(String postName) {
        // 调用compPostApi的listByName方法，根据查询参数的名称获取岗位列表
        return this.compPostApi.listByName(postName);
    }

    private List<ComponentUser> pickUser(List<String> userIds, String userName, String parentDeptId, Boolean dataScopeOnly) {
        // 如果用户ID或姓名不为空，则根据用户ID和姓名查询用户列表
        if (Tools.Coll.isNotBlank(userIds) || Tools.Str.isNotBlank(userName)) {
            return this.compUserApi.listByIdsAndName(userIds, userName);
        } else {
            // 否则根据部门ID查询用户列表
            return Boolean.TRUE.equals(dataScopeOnly) &&
                    Me.invalidDataScope(parentDeptId) ?
                    Collections.emptyList() :
                    this.compUserApi.listByDeptId(parentDeptId);
        }
    }

}
